package com.kdtech.analyse.video;
import java.util.Date;
import java.util.HashMap;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.analyse.AnalyseNews;

/**
 * 央视网
 * @author Persh
 */
public class CntvAnalyse implements AnalyseNews{



	public static HashMap<String,String>  getLinks(String sourceUrl) {
		// TODO Auto-generated method stub
		try {
			Date date = new Date();
			sourceUrl = StringUtils.substringBeforeLast(sourceUrl, "/");
			sourceUrl = sourceUrl+"/"+DateUtils.format(date,"yyyyMMdd")+".json";
			UrlMeta responseToURL = CrawlHTML.responseToURL(sourceUrl);
			JSONObject json = JSONObject.parseObject(responseToURL.getHtml());
			JSONArray array = json.getJSONArray("rollData");
			HashMap<String,String> links = new HashMap<String, String>();
			for(int i=0;i<array.size();i++){
				String url = array.getJSONObject(i).getString("url");
				links.put(url, null);
			}
			return links;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://.*.cntv.cn/.*[0-9]{8}/[0-9]{6}.shtml",
				"http://xiyou.cntv.cn/v-.{8}-.{4}-.{4}-.{4}-.*.html",
				"http://.*.cntv.cn/[0-9]{4}/[0-9]{2}/[0-9]{2}/VIDE[0-9]*.shtml(\\?ptag=.*)*",
				"http://tv.cntv.cn/video/.*"
				};

		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta video = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		video.setUrl(url);
		String title = null;
		String desc = null;
		Long date = null;
		Integer commentNum=0;
		Integer clickNum = 0;
		Document doc = Jsoup.parse(htmltxt);

		title = doc.select("div#container>div#top_title.top_title>h1.b-tit").text();
		if(StringUtils.isBlank(title)){
			if(StringUtils.isBlank(title)){
				title = doc.select("div.bread a.cur").text();
			}
			if(StringUtils.isBlank(title)){
				title = doc.select("div.bread").text();
			}
			if(title!=null && title.trim().length()>0){
				String[] split = title.split(">");
				if(split.length>3) title = split[2];
			}else{
				String titleHtml = doc.select("div#container").html();
				if(titleHtml.contains("video_page_title")){
					titleHtml = titleHtml.substring(titleHtml.indexOf("video_page_title=")+"video_page_title=".length(), titleHtml.indexOf("var video_page_create_time"));
					title = titleHtml.substring(titleHtml.indexOf("'")+1, titleHtml.lastIndexOf("'")).trim();
				}
				if(title==null || title.trim().length()==0){
					title = doc.select("div#watchvideo.box>h1.vtitle").text();
					if(title==null || title.trim().length()==0){
						title = doc.select("div.text_box>div.head_bar>h1").text();
						if(title==null || title.trim().length()==0){
							title = doc.select("div.videoBox>h1").text();
							if(title==null || title.trim().length()==0){
								title = doc.select("h2#title6").text();
							}
						}
					}
				}
			}
		}

		desc = doc.select("div#content_body").text();
		if(desc==null || desc.trim().length()==0){
			if(url.contains("http://xiyou.cntv.cn")){
				if(doc.select("div.relative>p").size()>0){
					desc = doc.select("div.relative>p").get(0).text();
				}
			}
			if(desc==null || desc.trim().length()==0){
				desc = doc.select("p#txt.txt").text();
			}
		}

		String tempdate=doc.select("div#container>div#top_title.top_title>p.art-info").text();
		if(tempdate==null || tempdate.trim().length()==0){
			String dateHtml = doc.select("div#container").html();
			if(dateHtml.contains("video_page_create_time")){
				tempdate = dateHtml.substring(dateHtml.indexOf("video_page_create_time='")+"video_page_create_time='".length(), dateHtml.indexOf("</script>"));
			}
			if(tempdate==null || tempdate.trim().length()==0){
				tempdate=doc.select("div#short_1.shortinfo>p.pt10 span.fsize11").text();
				if(tempdate==null || tempdate.trim().length()==0){
					tempdate=doc.select("div.videoinfo>p").text();
					if(tempdate==null || tempdate.trim().length()==0){
						tempdate=doc.select("span.videoUploadTime").text();
					}
				}
			}
		}
		
		date = DateUtils.matchDate(tempdate);

		if(date==null){
			date = DateUtils.matchDate(doc.select("META[name=publishdate]").attr("content"));
		}
		if(date==null){
			date = DateUtils.matchDate(url);
		}
		
		String author=null;
		author=doc.select("div#container div#top_title p.art-info").text();
		if(author!=null && author.indexOf("来源：")!=-1){
			author=StringUtils.substringBetween(author, "来源：", "|").trim();
		}
		if(StringUtils.isBlank(author)){
			author=doc.select("span#userName").text();
		}
		video.setAuthor(author);
		/**
		 * 解析用于更新的地址
		 */
		String updateUrl = null;
		if(url.contains("xiyou.cntv.cn")){
			String clickNumStr = doc.select("div.play_num").text();
			clickNumStr = clickNumStr.replaceAll(",", "");
			commentNum=NumberUtils.matchNumber(doc.select("a.btn_dig").text());
			clickNum=NumberUtils.matchNumber(clickNumStr);
			video.setCommentNum(commentNum);
			video.setClickNum(clickNum);
			updateUrl = url;
		}
		
		video.setTitle(StringUtils.trim(title));
		video.setContent(desc);
		video.setDate(date);
		if(updateUrl!=null){
			video.setUpdateUrl(updateUrl);
			NewsMeta update = Update(video);
			return update;
		}

		return video;
	}
	

	
	public NewsMeta Update(NewsMeta meta) {
		if (meta!=null) {
			String updateUrl = meta.getUpdateUrl();
			if (updateUrl != null) {
				UrlMeta responseToURL = CrawlHTML.responseToURL(updateUrl);
				if (responseToURL != null) {
					Document doc = Jsoup.parse(responseToURL.getHtml());
					Integer commentNum=0;
					Integer clickNum = 0;
					String clickNumStr = doc.select("div.play_num").text();
					clickNumStr = clickNumStr.replaceAll(",", "");
					commentNum=NumberUtils.matchNumber(doc.select("a.btn_dig").text());
					clickNum=NumberUtils.matchNumber(clickNumStr);
					meta.setCommentNum(commentNum);
					meta.setClickNum(clickNum);
				}
			}
		}
		return meta;
	}

	
}
